﻿using PmSadis.Repositories.Abstract;
using PmSadis.Models;
using System.Linq;
using PmSadis.Dal;
using System;
using System.Data.Entity;

namespace PmSadis.Repositories
{
    /// <summary>
    /// Хранилище работников справочных работ
    /// </summary>
    public class WorkWorkerRepository : IListRepository<WorkWorker>
    {
        private ModelsContext _context = new ModelsContext();

        /// <summary>
        /// Полный список работников
        /// </summary>
        public IQueryable<WorkWorker> All
        {
            get
            {
                return _context.WorkWorkers;
            }
        }

        /// <summary>
        /// Удалить материал
        /// </summary>
        /// <param name="id">Идентификатор работника</param>
        public void Delete(object id)
        {
            var workWorkerId = (int)id;
            var workWoker = _context.WorkWorkers.FirstOrDefault(x => x.WorkWorkerId == workWorkerId);
            if (workWoker == null) return;

            _context.WorkWorkers.Remove(workWoker);
            _context.SaveChanges();
        }

        /// <summary>
        /// Создать или редактировать работника
        /// </summary>
        /// <param name="workWorker">Работник</param>
        public object Edit(WorkWorker workWorker)
        {
            var dateNow = DateTime.Now;
            if (workWorker.WorkWorkerId == 0)
            {
                workWorker.DateCreate = dateNow;
                workWorker.DateUpdate = dateNow;
                _context.Entry(workWorker).State = EntityState.Added;
            }
            else
            {
                workWorker.DateUpdate = dateNow;
                _context.Entry(workWorker).State = EntityState.Modified;
            }

            _context.SaveChanges();

            return workWorker.WorkWorkerId;
        }
    }
}
